/*
 * @author  王克鸿
 * @date  2020/12/24 17:01
 * @version 1.0
 */
package com.smsVerification.controller;

import com.smsVerification.config.HttpCode;
import com.smsVerification.pojo.CommonResult;
import com.smsVerification.service.captcha.ICaptchaEditService;
import com.smsVerification.utils.EncryptValueHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Wang KeHong
 */
@Slf4j
@RestController
@RefreshScope
public class CaptchaEditController {

    final String REQUEST_URL_PREFIX = "/user-message/CaptchaEdit";

    @Resource
    ICaptchaEditService captchaEditService;

    /**
     * 用户信息AES加密秘钥
     */
    @Value("${user-info.aes-encrypt-key}")
    String userInfoAesEncryptKey;

    /**
     * 用户信息AES加密加盐偏移
     */
    @Value("${user-info.aes-encrypt-iv}")
    String userInfoAesEncryptIv;

    /**
     * 发送验证码
     *
     * @param encryptedPhoneNumber 加密的用户手机号
     * @return 是否发送成功
     */
    @PostMapping(REQUEST_URL_PREFIX + "/sendCaptcha")
    public CommonResult<Boolean> sendCaptcha(@RequestParam("encryptedPhoneNumber") String encryptedPhoneNumber) {
        //解密后的手机号
        String decryptedPhoneNumber = getDecryptUserInfoData(encryptedPhoneNumber);

        if (decryptedPhoneNumber == null) {
            return new CommonResult<>(HttpCode.WRONG_PARAM, "手机号加密验证失败", false);
        }

        return captchaEditService.sendCaptcha(decryptedPhoneNumber);
    }

    /**
     * 将用户加密的数据进行解密
     *
     * @param encryptedData 加密的数据
     * @return 解密的数据
     */
    private String getDecryptUserInfoData(String encryptedData) {
        return EncryptValueHandler.getAesCbcDecryptData(userInfoAesEncryptKey, userInfoAesEncryptIv, encryptedData);
    }


}
